package velox.jcr.mapper;

import java.util.HashSet;
import java.util.Set;

public class NestedThreadLocalSet<T> {
	private ThreadLocal<Entry> threadLocal = new ThreadLocal<Entry>();

	static class Entry {
		private int depth = 1;
		private Set<Object> set = new HashSet<Object>();
		
		public Set<Object> getSet() {
			return set;
		}

		public boolean decrease() {
			return --depth == 0;
		}

		public void increase() {
			depth++;
		}
		
	}

	public Set<Object> enter() {
		if (threadLocal.get() == null) {
			threadLocal.set(new Entry());
		} else {
			threadLocal.get().increase(); 
		}
		return threadLocal.get().getSet();
	}

	public void exit() {
		if (threadLocal.get() == null) {
			throw new IllegalStateException("Can't exit without matching enter");
		}
		
		if (threadLocal.get().decrease()) {
			threadLocal.set(null);
		}
	}
}
